package cn.nfwx.tv.controller;

import android.Manifest;
import android.app.Notification;
import android.arch.lifecycle.Lifecycle;
import android.arch.lifecycle.LifecycleObserver;
import android.arch.lifecycle.OnLifecycleEvent;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.ServiceConnection;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.IBinder;
import android.os.Looper;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.FragmentManager;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.tencent.mm.opensdk.modelmsg.SendMessageToWX;
import com.yanzhenjie.permission.Action;
import com.yanzhenjie.permission.AndPermission;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.List;

import cn.nfwx.tv.R;
import cn.nfwx.tv.base.BaseDialogFragment;
import cn.nfwx.tv.base.NFWXApplication;
import cn.nfwx.tv.callback.ResponseListener;
import cn.nfwx.tv.callback.ResponseWithFailListener;
import cn.nfwx.tv.helper.DialogFragmentHelper;
import cn.nfwx.tv.helper.PermissionHelper;
import cn.nfwx.tv.helper.ThreadHelper;
import cn.nfwx.tv.helper.ValueCallback;
import cn.nfwx.tv.manager.ShortVideoManager;
import cn.nfwx.tv.model.IjkShortVideo;
import cn.nfwx.tv.model.Result;
import cn.nfwx.tv.okhttp.CustomOkHttpClient;
import cn.nfwx.tv.okhttp.ResultCode;
import cn.nfwx.tv.okhttp.UrlHelper;
import cn.nfwx.tv.service.DownloadService;
import cn.nfwx.tv.util.AppUtil;
import cn.nfwx.tv.util.GlideUtil;
import cn.nfwx.tv.util.LogUtil;
import cn.nfwx.tv.util.MobAgentUtil;
import cn.nfwx.tv.util.ToastUtil;
import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;

/**
 * Created by zhouzechao on 2017/11/24.
 */
public class ShortVideoShareViewController extends BaseDialogFragment implements View.OnClickListener, DownloadService.DownloadProgressListener, Handler.Callback, LifecycleObserver, ResponseWithFailListener<String> {

    private final String TAG = ShortVideoShareViewController.class.getSimpleName();

    private final int ACTION_START = 1;
    private final int ACTION_UPDATE = 2;
    private final int ACTION_SUCCESS = 3;
    private final int ACTION_ERROR = 4;

    private final String KEY_START_TIME = "key_start_time";
    private final String KEY_END_TIME = "key_end_time";
    private final String KEY_PATH = "key_path";
    private final String KEY_UID = "key_uid";
    private final String KEY_NAME = "key_name";
    private final String KEY_STATS = "key_stats";
    private final String KEY_LIVEING_NAME = "key_liveing_name";

    private ImageView shareImage;
    private TextView tv_download_title;
    private ProgressBar loading_pro;
    private LinearLayout download_btn, weix_btn, pengy_btn;
    private TextView tv_download_note;

    private String shareUrl;
    private String downUrl;
    private String requestViewPathCommand, requestDownFileCommand, requestIjkVideoCommand;
    private String lid;
    private long startTimeCode, endTimeCode;
    private FragmentManager mFragmentManager;
    private String name;
    private String liveingName;
    private String clipPath;

    private boolean _isDownloading = false;
    private boolean _isDownloaded = false;

    private static final int STATS_P2P = 1;
    private static final int STATS_IJK = 2;

    private int stats;
    private String mStartTimeUrl;
    private String mEndTimeUrl;


    public static ShortVideoShareViewController newInstance() {
        ShortVideoShareViewController fragment = new ShortVideoShareViewController();
        return fragment;
    }

    /**
     * 是否填满整个屏幕
     */
    protected boolean isMatchParent() {
        return true;
    }

    protected boolean isOutsideTouchable() {
        return true;
    }

    //是否透明背景
    protected boolean isTranslucentBackground() {
        return true;
    }

    protected boolean isTranslucentStatus() {
        return false;
    }

    protected int getGravity() {
        return Gravity.BOTTOM;
    }

    @Override
    protected int getLayoutId() {
        return R.layout.dialog_share;
    }

    @Override
    protected void initView(Bundle savedInstanceState) {
        tv_download_note = findView(R.id.tv_download_note);
        shareImage = findView(R.id.shareImage);
        loading_pro = findView(R.id.loading_pro);
        download_btn = findView(R.id.download_btn);
        weix_btn = findView(R.id.weix_btn);
        pengy_btn = findView(R.id.pengy_btn);
        tv_download_title = findView(R.id.tv_download_title);

        loading_pro.setMax(100);
        loading_pro.setProgress(0);

        download_btn.setOnClickListener(this);
        weix_btn.setOnClickListener(this);
        pengy_btn.setOnClickListener(this);
        findView(R.id.tv_cancle_btn).setOnClickListener(this);
        getLifecycle().addObserver(this);
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        stats = getArguments().getInt(KEY_STATS, STATS_P2P);
        if (stats == STATS_P2P) {
            clipPath = getArguments().getString(KEY_PATH);
            lid = getArguments().getString(KEY_UID);
            startTimeCode = getArguments().getLong(KEY_START_TIME);
            endTimeCode = getArguments().getLong(KEY_END_TIME);
            name = getArguments().getString(KEY_NAME);
            liveingName = getArguments().getString(KEY_LIVEING_NAME);
            tv_download_title.setVisibility(View.VISIBLE);
            GlideUtil.loadImage(getContext(), UrlHelper.getThumbUrl(clipPath, startTimeCode / 1000L), shareImage);
        } else if (stats == STATS_IJK) {
            name = getArguments().getString(KEY_NAME);
            mStartTimeUrl = getArguments().getString(KEY_START_TIME);
            mEndTimeUrl = getArguments().getString(KEY_END_TIME);
            liveingName = getArguments().getString(KEY_LIVEING_NAME);
            GlideUtil.loadImage(getContext(), mStartTimeUrl, shareImage);
        }
    }

    @Override
    public void onDismiss(DialogInterface dialog) {
        //CustomOkHttpClient.cancleAll(requestViewPathCommand);
        super.onDismiss(dialog);
    }

    /**
     * 获取分享的视频地址
     *
     * @param fragmentManager
     * @param lid
     * @param startTime
     * @param endTime
     */
    public void requestVideoPath(FragmentManager fragmentManager, String lid, long startTime, long endTime) {
        mFragmentManager = fragmentManager;
        DialogFragmentHelper.showLoadingDialog(mFragmentManager, "加载中...");
        //requestViewPathCommand = ShortVideoManager.requestShortVideo(getContext(), lid, startTime, endTime, timeCallBack);
    }

    /**
     * 获取分享的视频地址
     *
     * @param fragmentManager
     * @param lid
     * @param startTime
     * @param endTime
     */
    public void requestVideoPath(FragmentManager fragmentManager, String lid, String startTime, String endTime) {
        mFragmentManager = fragmentManager;
        DialogFragmentHelper.showLoadingDialog(mFragmentManager, "加载中...");
        requestIjkVideoCommand = ShortVideoManager.requestIjkShortVideo(getContext(), lid, startTime, endTime, this);
    }

    /**
     * 下载短视频
     *
     * @param lid
     * @param startTime
     * @param endTime
     */
    private void down(Context context, String lid, long startTime, long endTime) {
        if (_isDownloading) {
            ToastUtil.show(getActivity(), "正在下载中");
            return;
        }
        if (_isDownloaded) {
            ToastUtil.show(getActivity(), "已经下载成功");
            return;
        }
        _isDownloaded = false;
        _isDownloading = false;
        String url = UrlHelper.getDownloadShortVideoUrl(lid, startTime, endTime);
        File mediaStorageDir = new File(Environment.getExternalStoragePublicDirectory(
                Environment.DIRECTORY_PICTURES), context.getString(R.string.app_name));
        DownloadService.Builder.create(url)
                .setStoreDir(mediaStorageDir.getPath())
                .setIsSendBroadcast(true)
                .setDownloadSuccessNotificationFlag(Notification.DEFAULT_SOUND)
                .setDownloadErrorNotificationFlag(Notification.DEFAULT_SOUND)
                .setFileName("VOD_" + liveingName.replace("/", "") + "_" + startTime + ".mp4")
                .setConnection(mConnection)
                .setIcoResId(R.mipmap.ic_launcher)
                .setIcoSmallResId(context.getApplicationInfo().icon)
                .setTitle(liveingName)
                .build(context);
    }

    /**
     * 下载短视频
     */
    private void down(Context context, String downUrl) {
        if (_isDownloading) {
            ToastUtil.show(getActivity(), "正在下载中");
            return;
        }
        if (_isDownloaded) {
            ToastUtil.show(getActivity(), "已经下载成功");
            return;
        }
        _isDownloaded = false;
        _isDownloading = false;
        File mediaStorageDir = new File(Environment.getExternalStoragePublicDirectory(
                Environment.DIRECTORY_PICTURES), context.getString(R.string.app_name));
        DownloadService.Builder.create(downUrl)
                .setStoreDir(mediaStorageDir.getPath())
                .setIsSendBroadcast(true)
                .setDownloadSuccessNotificationFlag(Notification.DEFAULT_SOUND)
                .setDownloadErrorNotificationFlag(Notification.DEFAULT_SOUND)
                .setFileName("VOD_" + liveingName.replace("/", "") + "_" + System.currentTimeMillis() / 1000L + ".mp4")
                .setConnection(mConnection)
                .setIcoResId(R.mipmap.ic_launcher)
                .setTitle(liveingName)
                .build(context);
    }

    /**
     * 服务绑定的回调，将作为参数传递给BindService方法
     */
    private boolean mBound;
    private DownloadService.DownloadBinder binder;
    private ServiceConnection mConnection = new ServiceConnection() {


        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            binder = (DownloadService.DownloadBinder) service;
            binder.setUpdateProgressListener(ShortVideoShareViewController.this);
            mBound = true;
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            binder.setUpdateProgressListener(null);
            mBound = false;
        }
    };

    /**
     * 设置截图模式
     *
     * @param uid
     * @param timeStart
     * @param timeEnd
     * @param name
     * @param liveingName
     */
    public void setData(String path, String uid, long timeStart, long timeEnd, String name, String liveingName) {
        LogUtil.e(TAG, timeStart + "---" + timeEnd);
        Bundle bundle = new Bundle();
        bundle.putInt(KEY_STATS, STATS_P2P);
        bundle.putString(KEY_PATH, path);
        bundle.putString(KEY_UID, uid);
        bundle.putLong(KEY_START_TIME, timeStart);
        bundle.putLong(KEY_END_TIME, timeEnd);
        bundle.putString(KEY_NAME, name);
        bundle.putString(KEY_LIVEING_NAME, liveingName);
        this.setArguments(bundle);
    }

    /**
     * @param startTime
     * @param endTime
     * @param liveingName
     */
    public void setData(String gid, String startTime, String endTime, String liveingName) {
        Bundle bundle = new Bundle();
        bundle.putInt(KEY_STATS, STATS_IJK);
        bundle.putString(KEY_NAME, gid);
        bundle.putString(KEY_START_TIME, startTime);
        bundle.putString(KEY_END_TIME, endTime);
        bundle.putString(KEY_LIVEING_NAME, liveingName);
        this.setArguments(bundle);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode) {
            case 400: { // 这个400就是上面defineSettingDialog()的第二个参数。
                if (AndPermission.hasPermissions(getActivity(), Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
                    //downloadShortVideo(lid, startTimeCode, endTimeCode);
                    if (stats == STATS_P2P) {
                        down(getContext(), lid, startTimeCode, endTimeCode);
                    } else if (stats == STATS_IJK) {
                        down(getContext(), downUrl);
                    }
                } else {
                    ToastUtil.show(getActivity(), "取消下载");
                }
                break;
            }
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.download_btn:
                if (!TextUtils.isEmpty(shareUrl)) {
                    PermissionHelper.getInstance().requestStoragePermission(this, new Action<List<String>>() {
                        @Override
                        public void onAction(List<String> grantedPermissions) {
                            if (!grantedPermissions.isEmpty() && grantedPermissions.contains(Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
                                if (stats == STATS_P2P) {
                                    down(getContext(), lid, startTimeCode, endTimeCode);
                                } else if (stats == STATS_IJK) {
                                    down(getContext(), downUrl);
                                }
                            } else {
                                if (AndPermission.hasAlwaysDeniedPermission(getActivity(), grantedPermissions)) {
                                    PermissionHelper.getInstance().showStorageSettingDialog(ShortVideoShareViewController.this);
                                } else {
                                    ToastUtil.show(getActivity(), "取消下载");
                                }
                            }
                        }
                    }, new Action<List<String>>() {
                        @Override
                        public void onAction(List<String> deniedPermissions) {
                            if (AndPermission.hasAlwaysDeniedPermission(getActivity(), deniedPermissions)) {
                                PermissionHelper.getInstance().showStorageSettingDialog(ShortVideoShareViewController.this);
                            } else {
                                ToastUtil.show(getActivity(), "取消下载");
                            }
                        }
                    });
                    MobAgentUtil.downloadClick(getActivity());
                } else {
                    ToastUtil.show(getContext(), "网络超时");
                }
                break;
            case R.id.weix_btn:
                if (!TextUtils.isEmpty(shareUrl)) {
                    share2WeiXin(SendMessageToWX.Req.WXSceneSession);
                    MobAgentUtil.shortClipWechatClick(getActivity());
                } else {
                    ToastUtil.show(getContext(), "网络超时");
                }
                break;
            case R.id.pengy_btn:
                if (!TextUtils.isEmpty(shareUrl)) {
                    share2WeiXin(SendMessageToWX.Req.WXSceneTimeline);
                    MobAgentUtil.shortClipFriendClick(getActivity());
                } else {
                    ToastUtil.show(getContext(), "网络超时");
                }
                break;
            case R.id.tv_cancle_btn:
                dismiss();
                break;
        }
    }

    private void share2WeiXin(final int wxSceneSession) {
        if (NFWXApplication.getInstance().getIwxapi().isWXAppInstalled()) {
            GlideUtil.downloadImage(NFWXApplication.getInstance(), mStartTimeUrl, new ValueCallback<File>() {
                @Override
                public void onReceiveValue(File value) {
                    if (value == null) {
                        GlideUtil.downloadImage(NFWXApplication.getInstance(), UrlHelper.getShareThumbUrl(), new ValueCallback<File>() {
                            @Override
                            public void onReceiveValue(File value) {
                                if (value == null) {
                                    return;
                                }
                                String des = "我用" + getString(R.string.app_name) + "APP给你截了一段精彩视频:" + liveingName;
                                try {
                                    AppUtil.shareWebPage2WeiXin(getContext(), wxSceneSession, shareUrl, liveingName, des, BitmapFactory.decodeStream(new FileInputStream(value)));
                                } catch (FileNotFoundException e) {
                                    e.printStackTrace();
                                }
                            }
                        });
                        return;
                    }
                    String des = "我用" + getString(R.string.app_name) + "APP给你截了一段精彩视频:" + liveingName;
                    try {
                        AppUtil.shareWebPage2WeiXin(getContext(), wxSceneSession, shareUrl, liveingName, des, BitmapFactory.decodeStream(new FileInputStream(value)));
                    } catch (FileNotFoundException e) {
                        e.printStackTrace();
                    }
                }
            });
        } else {
            ToastUtil.show(getContext(), "没有安装微信");
        }
    }

    /**
     * 下载回调
     */
    Handler proHandler = new Handler(this);

    @Override
    public void start(String requestTag) {
        _isDownloading = true;
        _isDownloaded = false;
        proHandler.sendEmptyMessage(ACTION_START);

    }

    @Override
    public void update(String requestTag, int progress) {
        _isDownloading = true;
        _isDownloaded = false;
        proHandler.sendMessage(proHandler.obtainMessage(ACTION_UPDATE, progress));

    }

    @Override
    public void success(String requestTag, String path) {
        _isDownloading = false;
        _isDownloaded = true;
        proHandler.sendMessage(proHandler.obtainMessage(ACTION_SUCCESS, path));
    }

    @Override
    public void error(String requestTag) {
        _isDownloading = false;
        _isDownloaded = true;
        proHandler.sendEmptyMessage(ACTION_ERROR);
    }

    @Override
    public boolean handleMessage(Message msg) {
        switch (msg.what) {
            case ACTION_START: // 正在下载
                tv_download_note.setVisibility(View.VISIBLE);
                break;
            case ACTION_UPDATE:
                loading_pro.setVisibility(View.VISIBLE);
                tv_download_title.setVisibility(View.VISIBLE);
                loading_pro.setProgress((Integer) msg.obj);
                break;
            case ACTION_SUCCESS: // 下载完成
                tv_download_title.setVisibility(View.VISIBLE);
                tv_download_title.setText(R.string.downed_note);
                tv_download_note.setVisibility(View.GONE);
                //ToastUtil.show(NFWXApplication.getInstance(), R.string.downed_note);
                loading_pro.setVisibility(View.GONE);
                String filePath = (String) msg.obj;
                if (!TextUtils.isEmpty(filePath)) {
                    File file = new File(filePath);
                    Uri localUri = Uri.fromFile(file);
                    Intent localIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, localUri);
                    NFWXApplication.getInstance().sendBroadcast(localIntent);
                }
                break;
            case ACTION_ERROR: // 下载失败
                loading_pro.setVisibility(View.GONE);
                break;
        }
        return false;
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_STOP)
    public void release() {
        CustomOkHttpClient.cancleAll(requestViewPathCommand);
        if (mBound) {
            if (getContext() != null) {
                getContext().unbindService(mConnection);
            }
            mBound = false;
        }
        if (binder != null) {
            binder.setUpdateProgressListener(null);
        }
        DownloadService.stop(getActivity());
        proHandler.removeCallbacksAndMessages(null);
    }

    @Override
    public void onResponse(String requestTag, final String response) {
        if (requestTag.equals(requestViewPathCommand)) { // 请求详情
            Observable.create(new ObservableOnSubscribe<Result<String>>() {
                @Override
                public void subscribe(ObservableEmitter<Result<String>> emitter) {
                    Result<String> result = JSON.parseObject(response, new TypeReference<Result<String>>() {
                    }.getType());
                    emitter.onNext(result);
                    emitter.onComplete();
                }
            }).subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .compose(this.<Result<String>>bindToLifecycle())
                    .subscribe(new Observer<Result<String>>() {
                        @Override
                        public void onSubscribe(Disposable d) {

                        }

                        @Override
                        public void onNext(Result<String> result) {
                            if (Result.RESULT_SUCCESS.equals(result.getMessage())) {
                                shareUrl = result.getData();
                            } else {
                                ToastUtil.show(getContext(), result.getData());
                            }
                        }

                        @Override
                        public void onError(Throwable e) {

                        }

                        @Override
                        public void onComplete() {
                            DialogFragmentHelper.closeLoadingDialog(mFragmentManager);
                        }
                    });
        } else if (requestTag.equals(requestIjkVideoCommand)) {
            Observable.create(new ObservableOnSubscribe<Result<IjkShortVideo>>() {
                @Override
                public void subscribe(ObservableEmitter<Result<IjkShortVideo>> emitter) {
                    Result<IjkShortVideo> result = JSON.parseObject(response, new TypeReference<cn.nfwx.tv.model.Result<IjkShortVideo>>() {
                    }.getType());
                    emitter.onNext(result);
                    emitter.onComplete();
                }
            }).subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .compose(this.<Result<IjkShortVideo>>bindToLifecycle())
                    .subscribe(new Observer<Result<IjkShortVideo>>() {
                        @Override
                        public void onSubscribe(Disposable d) {

                        }

                        @Override
                        public void onNext(Result<IjkShortVideo> result) {
                            if (result.getCode() == 0) {
                                shareUrl = result.getData().getM3u8();
                                downUrl = result.getData().getMp4();
                            } else {
                                ToastUtil.show(getContext(), result.getMessage());
                            }
                        }

                        @Override
                        public void onError(Throwable e) {

                        }

                        @Override
                        public void onComplete() {
                            DialogFragmentHelper.closeLoadingDialog(mFragmentManager);
                        }
                    });
        }
    }

    @Override
    public void onError(String requestTag, Throwable t) {

    }

    @Override
    public void onFinish() {

    }

    @Override
    public void onFail(String requestTag, String response) {

    }
}
